<template>
  <el-dialog
    title="更新数据"
    width="30%"
    :append-to-body="true"
    :visible.sync="showTag"
  >
    <span>正在更新{{ form.name }} {{ action }}</span>
  </el-dialog>
</template>

<script>
export default {
  name: "SurveyCacheUpdateDialog",
  data() {
    return {
      form: {},
      action: "",
      showTag: false
    };
  },
  methods: {
    show(id) {
      this.showTag = true;
      if (id) {
        this.doUpdateById(id);
      } else {
        this.doUpdate(1);
      }
    },
    hide() {
      this.showTag = false;
    },
    async doUpdateById(id) {
      this.form = await this.$surveyService.detail(id);
      await this.updateSort();
      await this.updateAuthor();
      await this.updateQuestions();
      this.$emit("ok");
      this.hide();
    },
    async doUpdate(pageNum) {
      const data = await this.$surveyService.list({
        pageSize: 1,
        pageNum
      });
      if (data && data.data && data.data.length) {
        this.form = data.data[0];
        await this.updateSort();
        await this.updateAuthor();
        await this.updateQuestions();
        await this.doUpdate(++pageNum);
      } else {
        this.$emit("ok");
        this.hide();
      }
    },

    async updateAuthor() {
      this.action = "发布者";
      // eslint-disable-next-line camelcase
      const { author_id, author_type, id, author_name: old_name } = this.form;
      // eslint-disable-next-line camelcase
      if (author_id) {
        // eslint-disable-next-line camelcase
        let name, author_name;
        // eslint-disable-next-line camelcase
        if (author_type === "admin") {
          // eslint-disable-next-line camelcase
          const { name: name1 } = await this.$adminService.detail(author_id);
          // eslint-disable-next-line camelcase
          author_name = name1;
        }
        // eslint-disable-next-line camelcase
        if (old_name !== author_name) {
          await this.$surveyService.update({
            id,
            // eslint-disable-next-line camelcase
            author_name: author_name || name
          });
        }
      }
    },

    async updateQuestions() {
      this.action = "题目数";
      const { form } = this;
      const data = await this.$surveyService.questionList({
        survey_id: form.id
      });
      await this.$surveyService.update({
        id: form.id,
        questions: data.count
      });
    },

    async updateSort() {
      this.action = "排序";
      const { form } = this;
      if (!form.sort) {
        await this.$surveyService.update({ id: form.id, sort: form.id });
      }
    }
  }
};
</script>

<style scoped></style>
